<template>
  <div class="search-container">
    <!-- 顶部导航 -->
    <div class="nav-header">
      <div class="back-btn" @click="router.back()">
        <span class="back-icon">←</span>
      </div>
      <h2>搜索</h2>
    </div>

    <!-- 搜索区域 -->
    <div class="search-section">
      <div class="search-box">
        <input
          v-model="searchQuery"
          type="text"
          placeholder="搜索你喜欢的饮品"
          @input="handleSearch"
          @focus="showSearchContent = true"
        />
        <i class="search-icon">🔍</i>
      </div>
    </div>

    <!-- 搜索内容区域 -->
    <div class="search-content" v-if="showSearchContent && !searchQuery">
      <!-- 热门搜索 -->
      <div class="hot-search">
        <h3>热门搜索</h3>
        <div class="hot-tags">
          <span
            v-for="tag in hotSearchTags"
            :key="tag"
            class="hot-tag"
            @click="selectHotSearch(tag)"
          >
            {{ tag }}
          </span>
        </div>
      </div>

      <!-- 搜索历史 -->
      <div class="search-history" v-if="searchHistory.length > 0">
        <div class="history-header">
          <h3>搜索历史</h3>
          <span class="clear-history" @click="clearHistory">清空历史</span>
        </div>
        <div class="history-list">
          <div
            v-for="(item, index) in searchHistory"
            :key="index"
            class="history-item"
            @click="selectHistoryItem(item)"
          >
            <span class="history-text">{{ item }}</span>
            <span class="delete-history" @click.stop="deleteHistoryItem(index)">×</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 搜索结果 -->
    <div class="search-results" v-if="searchQuery">
      <div v-if="loading" class="loading">搜索中...</div>
      <div v-else-if="error" class="error">{{ error }}</div>
      <div v-else-if="searchResults.length === 0" class="no-results">
        未找到相关商品
      </div>
      <div v-else class="results-list">
        <div
          v-for="item in searchResults"
          :key="item.id"
          class="result-item"
          @click="router.push(`/shopping/detail/${item.id}`)"
        >
          <div class="item-image">
            <img v-if="item.image" :src="`http://localhost:3005/${item.image}`" :alt="item.title">
          </div>
          <div class="item-info">
            <h3>{{ item.title }}</h3>
            <div class="item-tags">
              <span class="tag" v-for="tag in item.tags" :key="tag">{{ tag }}</span>
            </div>
            <div class="item-price">¥{{ item.price }}</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const searchQuery = ref('')
// 示例商品数据
const mockProducts = [
  {
    id: 1,
    title: '美式咖啡',
    tags: ['经典', '热销'],
    price: 18,
    image: 'uploads/americano.jpg'
  },
  {
    id: 2,
    title: '拿铁咖啡',
    tags: ['奶香', '经典'],
    price: 22,
    image: 'uploads/latte.jpg'
  },
  {
    id: 3,
    title: '冰萃咖啡',
    tags: ['清爽', '限定'],
    price: 25,
    image: 'uploads/coldbrew.jpg'
  },
  {
    id: 4,
    title: '生椰拿铁',
    tags: ['椰香', '人气'],
    price: 26,
    image: 'uploads/coconut-latte.jpg'
  },
  {
    id: 5,
    title: '抹茶拿铁',
    tags: ['抹茶', '奶香'],
    price: 24,
    image: 'uploads/matcha-latte.jpg'
  },
  {
    id: 6,
    title: '茶拿铁',
    tags: ['茶香', '经典'],
    price: 20,
    image: 'uploads/tea-latte.jpg'
  },
  {
    id: 7,
    title: '瑞纳冰',
    tags: ['特调', '限定'],
    price: 28,
    image: 'uploads/rena-ice.jpg'
  },
  {
    id: 8,
    title: '芝士茗茶',
    tags: ['茶饮', '芝士'],
    price: 23,
    image: 'uploads/cheese-tea.jpg'
  }
]

const searchResults = ref([])
const loading = ref(false)
const error = ref('')
const showSearchContent = ref(false)

// 热门搜索标签
const hotSearchTags = ref([
  '美式咖啡',
  '拿铁',
  '冰萃咖啡',
  '生椰拿铁',
  '抹茶拿铁',
  '茶拿铁',
  '瑞纳冰',
  '芝士茗茶'
])

// 搜索历史
const searchHistory = ref<string[]>([])

// 初始化搜索历史
onMounted(() => {
  const history = localStorage.getItem('searchHistory')
  if (history) {
    searchHistory.value = JSON.parse(history)
  }
})

// 保存搜索历史
const saveSearchHistory = (query: string) => {
  if (!query.trim()) return
  const index = searchHistory.value.indexOf(query)
  if (index > -1) {
    searchHistory.value.splice(index, 1)
  }
  searchHistory.value.unshift(query)
  if (searchHistory.value.length > 10) {
    searchHistory.value.pop()
  }
  localStorage.setItem('searchHistory', JSON.stringify(searchHistory.value))
}

// 清空历史
const clearHistory = () => {
  searchHistory.value = []
  localStorage.removeItem('searchHistory')
}

// 删除单个历史记录
const deleteHistoryItem = (index: number) => {
  searchHistory.value.splice(index, 1)
  localStorage.setItem('searchHistory', JSON.stringify(searchHistory.value))
}

// 选择热门搜索
const selectHotSearch = (tag: string) => {
  searchQuery.value = tag
  showSearchContent.value = false
  handleSearch()
}

// 选择历史记录
const selectHistoryItem = (item: string) => {
  searchQuery.value = item
  showSearchContent.value = false
  handleSearch()
}

// 处理搜索逻辑
const handleSearch = () => {
  if (!searchQuery.value.trim()) {
    searchResults.value = []
    return
  }

  loading.value = true
  error.value = ''
  saveSearchHistory(searchQuery.value)

  try {
    const query = searchQuery.value.toLowerCase().trim()
    searchResults.value = mockProducts.filter(product => 
      product.title.toLowerCase().includes(query) ||
      product.tags.some(tag => tag.toLowerCase().includes(query))
    )
    showSearchContent.value = false
  } catch (err) {
    error.value = '搜索出错，请稍后重试'
    console.error('Search error:', err)
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.search-container {
  padding: 0 0 80px 0;
  background-color: #f8f9fa;
  min-height: 100vh;
}

.nav-header {
  display: flex;
  align-items: center;
  padding: 16px 20px;
  background: #00b06b;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
  color: white;
}

.back-icon {
  font-size: 24px;
  margin-right: 20px;
  cursor: pointer;
}

.nav-header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 500;
}

.search-section {
    width: 400px;
  padding: 80px 15px 20px;
  background: #fff;
}

.search-box {
  position: relative;
  display: flex;
  align-items: center;
}

.search-box input {
  width: 100%;
  padding: 12px 40px 12px 16px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  font-size: 15px;
  outline: none;
  background: #f5f5f5;
}

.search-box input::placeholder {
  color: #999;
}

.search-icon {
  position: absolute;
  right: 16px;
  color: #666;
}

.search-content {
  background: #fff;
  padding: 20px;
}

.hot-search h3,
.search-history h3 {
  font-size: 16px;
  color: #333;
  margin: 0 0 16px;
  font-weight: 500;
}

.hot-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.hot-tag {
  padding: 8px 16px;
  background: #f5f5f5;
  border-radius: 20px;
  font-size: 14px;
  color: #333;
  cursor: pointer;
}

.hot-tag:hover {
  background: #e0e0e0;
}

.search-history {
  margin-top: 24px;
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.clear-history {
  font-size: 14px;
  color: #999;
  cursor: pointer;
}

.history-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.history-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  cursor: pointer;
}

.history-text {
  font-size: 14px;
  color: #666;
}

.delete-history {
  font-size: 16px;
  color: #999;
  padding: 4px 8px;
}

.delete-history:hover {
  color: #666;
}

.search-results {
  padding: 20px;
}

.loading,
.error,
.no-results {
  text-align: center;
  padding: 20px;
  color: #666;
}

.results-list {
  display: grid;
  gap: 16px;
}

.result-item {
  display: flex;
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  cursor: pointer;
}

.item-image {
  width: 120px;
  height: 120px;
  overflow: hidden;
}

.item-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.item-info {
  flex: 1;
  padding: 12px;
}

.item-info h3 {
  margin: 0 0 8px;
  font-size: 16px;
  color: #333;
}

.item-tags {
  display: flex;
  gap: 8px;
  margin-bottom: 8px;
}

.tag {
  padding: 2px 8px;
  background: #f0f0f0;
  border-radius: 12px;
  font-size: 12px;
  color: #666;
}

.item-price {
  font-size: 18px;
  font-weight: bold;
  color: #42b883;
}
</style>